package com.gitee.maskit.web;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.TimeZone;
import java.util.function.Function;

/**
 * @author z0228
 */
@Slf4j
public class WebFilter implements Filter {
    private static final int GMT_OFFSET = TimeZone.getDefault().getRawOffset();
    private static final Function<Long, Long> GMT = time -> time - GMT_OFFSET;

    public static final String NAME = "MaskitWebFilter";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final long startAt = System.currentTimeMillis();

        WebHolder.REQUEST.set(servletRequest);
        WebHolder.RESPONSE.set(servletResponse);

        WebHolder.LOCALE.set(servletRequest.getLocale());

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            if (log.isDebugEnabled()) {
                log.debug("Handled request [{}] in [{}]ms from [{}]",
                    ((HttpServletRequest) servletRequest).getRequestURI(),
                    System.currentTimeMillis() - startAt,
                    GMT.apply(startAt));
            }
        }
    }

    @Override
    public void destroy() {
        WebHolder.clearAll();
    }
}
